package com.lagou;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class ConsumerApplication {

    public static void main(String[] args) throws InterruptedException, IOException {
        ApplicationContext context = SpringApplication.run(ConsumerApplication.class, args);

        // 获取方法对象
        HelloClient helloClient = context.getBean(HelloClient.class);
        // 设定调用总次数
        int c = 10000000;
        CountDownLatch cl = new CountDownLatch(c);

        // 创建调用线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setQueueCapacity(5000);
        taskExecutor.setCorePoolSize(200);
        taskExecutor.initialize();

        Random rd = new Random();

        Runnable ra = () -> {
            // 随机调用 A B C 三个方法
            int r = rd.nextInt(3);
            try {
                switch (r) {
                    case 0:
                        helloClient.methodA();
                        break;
                    case 1:
                        helloClient.methodB();
                        break;
                    case 2:
                        helloClient.methodC();
                        break;
                    default:
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            } finally {
                cl.countDown();
            }
        };

        while (c >= 0) {
            // 循环创建线程
            taskExecutor.submit(ra);
            c--;
            TimeUnit.MILLISECONDS.sleep(1);
        }
        cl.await();
    }
}
